package com.smartleanx.module.hrm.service.esign.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.dal.dataobject.esign.ContractOrder;
import com.smartleanx.module.hrm.dal.dataobject.esign.ContractPackage;
import com.smartleanx.module.hrm.dal.dataobject.esign.SystemConfig;
import com.smartleanx.module.hrm.dal.mysql.employee.EmployeeMapper;
import com.smartleanx.module.hrm.dal.mysql.esign.ContractOrderMapper;
import com.smartleanx.module.hrm.dal.mysql.esign.ContractPackageMapper;
import com.smartleanx.module.hrm.dal.mysql.esign.SystemConfigMapper;
import com.smartleanx.module.hrm.service.esign.service.ContractPackageService;
import com.smartleanx.module.hrm.service.examine.util.exception.ResultException;
import com.smartleanx.module.hrm.util.DateUtil;
import com.smartleanx.module.hrm.util.GenerateOrderSn;
import com.smartleanx.module.hrm.util.RestUtil.RestTemplateUtil;
import org.apache.ibatis.executor.result.ResultMapException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2025-07-14
 */
@Service
public class ContractPackageServiceImpl implements ContractPackageService {

    @Autowired
    private ContractPackageMapper contractPackageMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ContractOrderMapper contractOrderMapper;

    @Autowired
    private SystemConfigMapper systemConfigMapper;

    @Override
    public List<ContractPackage> selectList() {
        List<ContractPackage> contractPackages = contractPackageMapper.selectList(new LambdaQueryWrapper<ContractPackage>() {{
        }});
        contractPackages.forEach(contractPackage -> {
            LocalDate currentDate = LocalDate.now();
            LocalDate localDate = currentDate.plusMonths(contractPackage.getContractTime());
            String startTime = DateUtil.localDataParseStr(currentDate);
            String endTime = DateUtil.localDataParseStr(localDate);
            contractPackage.setStartTime(startTime);
            contractPackage.setEndTime(endTime);
        });
        JSONObject result = new JSONObject();
        result.put("contractPackages", contractPackages);
        if (contractPackages.size() > 0) {
            result.put("amount", contractPackages.get(0).getContractAmount());
        }
        result.put("amount", 0.00);
        return contractPackages;
    }



    @Override
    public ContractOrder generationOrder(Integer packageId, String orderSn, Integer loginId, Integer payNum) {
        ContractOrder contractOrder = null;
        ContractPackage contractPackage = null;
        if (ObjectUtils.isEmpty(orderSn)) {
            String orderSnNew = GenerateOrderSn.getOrderSn();
            contractPackage = contractPackageMapper.selectById(packageId);
            if (ObjectUtils.isEmpty(contractPackage)) {
                throw new ResultMapException("套餐不存在请刷新页面憨");
            }
            EmployeeDO employeeDO = employeeMapper.selectOne(new LambdaQueryWrapper<EmployeeDO>() {{
                eq(EmployeeDO::getUserId, loginId);
            }});
            if (ObjectUtils.isEmpty(employeeDO)) {
                throw new ResultMapException("此账号不可以购买套餐");
            }
            // 计算起始时间
            LocalDate currentDate = LocalDate.now();
            LocalDate localDate = currentDate.plusMonths(contractPackage.getContractTime());
            String startTime = DateUtil.localDataParseStr(currentDate);
            String endTime = DateUtil.localDataParseStr(localDate);
            //设置订单超时时间十五分钟
            String timeExpire = DateUtil.dateFormat();
            contractOrder = new ContractOrder();
            contractOrder.setOrderSn(orderSnNew);
            contractOrder.setContractNum(contractPackage.getContractNum() * payNum);
            contractOrder.setOrderAmount(new BigDecimal(contractPackage.getContractNum()).multiply(new BigDecimal(payNum)).multiply(contractPackage.getContractAmount()));
            contractOrder.setOrderStatus(1);
            contractOrder.setUsedContractNum(0);
            contractOrder.setStartTime(startTime);
            contractOrder.setEndTime(endTime);
            contractOrder.setCreateBy(employeeDO.getId().intValue());
            contractOrder.setUserId(employeeDO.getUserId().intValue());
            contractOrder.setDeptId(employeeDO.getDeptId().intValue());
            contractOrder.setTenantId(employeeDO.getTenantId().toString());
            contractOrder.setPaymentSn(contractOrder.getOrderSn());
            contractOrder.setCreateTime(DateUtil.currentDateFormat());
            contractOrder.setPackageId(packageId);
            contractOrder.setTimeExpire(timeExpire);
            contractOrder.setCreateByName(employeeDO.getName());
            contractOrderMapper.insert(contractOrder);
            return contractOrder;
        } else {
            contractOrder = contractOrderMapper.selectOne(new LambdaQueryWrapper<ContractOrder>() {{
                eq(ContractOrder::getOrderSn, orderSn);
            }});
//            contractPackageMapper.selectById(packageId);
            Date date = DateUtil.stringToDate(contractOrder.getTimeExpire());
            if (date.getTime() < new Date().getTime()) {
                throw new ResultException("当前订单已超时");
            } else {
                return contractOrder;
            }
        }

    }


    @Override
    public String pay(Integer payType, String orderSn, Integer loginId) {
        ContractOrder contractOrder = contractOrderMapper.selectOne(new LambdaQueryWrapper<ContractOrder>() {{
            eq(ContractOrder::getOrderSn, orderSn);
        }});
        EmployeeDO employeeDO = employeeMapper.selectByUserId(loginId.longValue());
        Date date = DateUtil.stringToDate(contractOrder.getTimeExpire());
        System.err.println(date.getTime() + "超时时间");
        System.err.println(new Date().getTime() + "当前时间");
        if (date.getTime() < new Date().getTime()) {
            throw new ResultException("当前订单已超时");
        } else {
            //微信支付
            if (payType == 1) {
                System.err.println("微信支付");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orderSn", orderSn);
                ResponseEntity<String> jsonObjectResponseEntity = RestTemplateUtil.jsonPost("https://pay.laoanxin.cn/contractOrder/wxPay", jsonObject.toJSONString());
                jsonObjectResponseEntity.getBody();
                System.err.println("微信支付响应" + jsonObjectResponseEntity);
                System.err.println("微信" + jsonObjectResponseEntity.getBody());
                return jsonObjectResponseEntity.getBody();
            }

            //支付宝支付
            else if (payType == 2) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("employeeId", employeeDO.getId());
                jsonObject.put("orderSn", orderSn);
                ResponseEntity<String> jsonObjectResponseEntity = RestTemplateUtil.jsonPost("https://pay.laoanxin.cn/contractOrder/alyPay", jsonObject.toJSONString());
                jsonObjectResponseEntity.getBody();
                System.err.println("支付宝" + jsonObjectResponseEntity.getBody());
                return jsonObjectResponseEntity.getBody();
            }
        }
        return "";
    }


    @Override
    public List<JSONObject> bySelect() {
        List<JSONObject> resultList = new ArrayList<>();
        List<ContractPackage> contractPackages = contractPackageMapper.selectList(new LambdaQueryWrapper<ContractPackage>() {{
        }});
        contractPackages.forEach(contractPackage -> {
            JSONObject result = new JSONObject();
            result.put("id", contractPackage.getId());
            result.put("value", contractPackage.getContractNum() + "份");
            result.put("num", contractPackage.getContractNum());
            result.put("amount", contractPackage.getContractAmount());
            resultList.add(result);
        });
        return resultList;
    }


    @Override
    public Integer usedContract(Long num,String tenantId) {
        SystemConfig systemConfig = systemConfigMapper.selectOne(new LambdaQueryWrapper<SystemConfig>() {{
            eq(SystemConfig::getTenantId, tenantId);
        }});
        if (ObjectUtils.isEmpty(systemConfig)) {
            return 0;
        } else {
            if (systemConfig.getContractNum() - systemConfig.getUsedNum() < num) {
                return 0;
            } else {
                systemConfig.setUsedNum(systemConfig.getUsedNum() + num);
                systemConfigMapper.updateById(systemConfig);
                JSONObject param = new JSONObject();
                param.put("tenantId", systemConfig.getTenantId());
                param.put("usedNum", num);
                try {
                    RestTemplateUtil.jsonPost("http://43.138.110.225:8090/api/contractOrder/saveContractPayData", param.toJSONString());
                } catch (Exception e) {
                    System.err.println("同步开通平台错误" + e.getMessage());
                }
                return 1;
            }
        }
    }

    @Override
    public Boolean isUsed(Long num) {
        SystemConfig systemConfig = systemConfigMapper.selectOne(null);
        if (ObjectUtils.isEmpty(systemConfig)) {
            return false;
        } else {
            if (systemConfig.getContractNum() - systemConfig.getUsedNum() < num) {
                return false;
            } else {

                return true;
            }
        }


    }


    @Override
    public JSONObject selectOneByContract() {
        JSONObject result = new JSONObject();
        SystemConfig systemConfig = systemConfigMapper.selectOne(null);
        if (!ObjectUtils.isEmpty(systemConfig)) {
            result.put("contractNum", systemConfig.getContractNum() - systemConfig.getUsedNum());
            result.put("usedNum", systemConfig.getUsedNum());

        } else {
            result.put("contractNum", 0);
            result.put("usedNum", 0);
        }

        return result;
    }

    @Override
    public Integer cancelPay(String orderSn) {
        ContractOrder contractOrder = contractOrderMapper.selectOne(new LambdaQueryWrapper<ContractOrder>() {{
            eq(ContractOrder::getOrderSn, orderSn);
        }});
        if (ObjectUtils.isEmpty(contractOrder)) {
            throw new ResultMapException("订单不存在");
        }
        if (contractOrder.getOrderStatus() == 2) {
            throw new ResultMapException("订单已支付成功");
        }
        contractOrder.setOrderStatus(5);
        contractOrderMapper.updateById(contractOrder);
        return 0;
    }

    @Override
    public Integer insert(JSONObject param) {
        String contractNumStr = param.getString("contractNumStr");
        BigDecimal contractAmount = param.getBigDecimal("contractAmount");
        Integer month = param.getInteger("month");
        Long initNum = param.getLong("initNum");
        List<Integer> contractNumList = Arrays.stream(contractNumStr.split(",")).map(c -> Integer.parseInt(c)).collect(Collectors.toList());
        contractPackageMapper.delete(null);
        contractNumList.forEach(contractNum -> {
            ContractPackage contractPackage = new ContractPackage();
            contractPackage.setContractNum(contractNum);
            contractPackage.setContractAmount(contractAmount);
            contractPackage.setContractTime(month);
            contractPackage.setInitNum(initNum);
            contractPackageMapper.insert(contractPackage);
        });
        return 0;
    }



    @Override
    public JSONObject select() {
        List<ContractPackage> contractPackages = contractPackageMapper.selectList();
        if (ObjectUtils.isEmpty(contractPackages)) {
            JSONObject result = new JSONObject();
            result.put("contractNumStr", "");
            result.put("contractAmount", "");
            result.put("month", "");
            result.put("initNum", "");
            return result;
        } else {
            String contractNumStr = contractPackages.stream().filter(contractPackage -> contractPackage.getContractNum() > 0).map(contractPackage -> contractPackage.getContractNum().toString()).collect(Collectors.joining(","));
            JSONObject result = new JSONObject();
            result.put("contractNumStr", contractNumStr);
            result.put("contractAmount", contractPackages.get(0).getContractAmount().compareTo(BigDecimal.ZERO) > 0 ? contractPackages.get(0).getContractAmount() : "");
            result.put("month", contractPackages.get(0).getContractTime() > 0 ? contractPackages.get(0).getContractTime().toString() : "");
            result.put("initNum", contractPackages.get(0).getInitNum() > 0 ? contractPackages.get(0).getInitNum().toString() : "");
            return result;
        }
    }


    @Override
    public Integer selectOrderStatus(String orderSn) {

        ContractOrder contractOrder = contractOrderMapper.selectOne(new LambdaQueryWrapper<ContractOrder>() {{
            eq(ContractOrder::getOrderSn, orderSn);
        }});
        if (contractOrder.getOrderStatus()==2){
            return 1;
        }
        return 0;
    }


}
